import { createRouter, createWebHistory } from 'vue-router'
import MapView from '../views/Map.vue'
import Login from '../components/Login.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/',
      name: 'home',
      component: MapView,
      meta: { requiresAuth: true }
    },
    {
      path: '/entertainment',
      name: 'entertainment',
      component: () => import("../views/entertainment.vue"),
      meta: { requiresAuth: true }
    }
  ]
})

router.beforeEach((to, _from, next) => {
  if (to.path === '/login') {
    next();
  } 
  else {
    const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true';
    if (to.matched.some(record => record.meta.requiresAuth) && !isLoggedIn) {
      next('/login');
    } else {
      next();
    }
  }
})

export default router